<template>
  <q-page class="q-pa-md" v-loading="loading">
    <div>
      <q-breadcrumbs class="q-mb-md" style="height:50px;line-height: 40px; border-bottom: 1px dashed #ccc;">
        <el-icon style="cursor: pointer;" @click="router.go(-1)">
          <ArrowLeft />
        </el-icon>
        <q-breadcrumbs-el label="通用管理" />
        <q-breadcrumbs-el label="用户管理" />
      </q-breadcrumbs>
      <div style="width: 60%">
        <el-form
          ref="ruleFormRef"
          :validate-on-rule-change="false"
          :model="addUseDialogData"
          :rules="isEditOrAdd?rules:rulesChange"
          status-icon
          label-width="100px"
          style="position:relative;width: 100%"
          :label-position="'left'"
        >
          <el-form-item label="用户名:" prop="username">
            <el-input spellcheck="false" v-model.trim="addUseDialogData.username" placeholder="用户名" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="邮箱:" prop="email">
            <el-input spellcheck="false" v-model.trim="addUseDialogData.email" placeholder="请输入邮箱" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="密码:" prop="password">
            <el-input spellcheck="false" v-model.trim="addUseDialogData.password" :placeholder="placeholder" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="角色选择:" prop="role_id">
            <el-radio-group v-model.number="addUseDialogData.role_id">
              <el-radio :label="1" name="type">系统超级管理员</el-radio>
              <el-radio :label="2" name="type">普通用户</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注说明:">
            <el-input spellcheck="false" type="textarea" v-model.trim="addUseDialogData.memo" placeholder="多行输入" :rows="4" />
          </el-form-item>
          <el-form-item class="dialog-footer">
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </q-page>
</template>
<script lang="ts" setup>
import {ref,reactive,nextTick} from "vue";
import type { FormInstance, FormRules } from 'element-plus'
import {addUsers, modifyUserInfo, usernameAndEmailExist} from "src/api/system";
import {ElMessage} from "element-plus";
import { useRouter } from 'vue-router';
const router = useRouter()
import {modelStore} from "stores/model";
const showModelStore = modelStore()
let projectId = router.currentRoute.value.params.project_id;
let loading = ref(false);
const ruleFormRef = ref<FormInstance>()
let isEditOrAdd = showModelStore.getIsEditOrAdd;
let placeholder = ref('');
let addUseDialogData = ref({
  username: '',
  email: '',
  password: 'a123456',
  role_id: '',
  memo: '',
  id: -1
});
//邮箱加验证
//新增
const validateUsername = (rule: any, value: any, callback: any) => {
  const params = reactive({
    username: addUseDialogData.value.username
  })
  if (!value) {
    callback(new Error('请输入用户名'))
  }
  if(/\s/g.test(value)){
    callback(new Error('用户名不能包含空格'))
  }else{
    usernameAndEmailExist(params).then((res: any) => {
      callback();
    }).catch(error => {
      callback(new Error(error.response.data[0]))
    })
  }
}//用户名
let checkEmail = (rule:any, value:any, callback:any) => {
  const params = reactive({
    email: addUseDialogData.value.email
  })
  if (!value) {
    return callback(new Error('请输入邮箱!'))
  }
  // 邮箱正则表达式
  const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{3,6}$/
  if (regEmail.test(value)) {
    // True 合法的邮箱
    usernameAndEmailExist(params).then((res: any) => {
      return callback();
    }).catch(error => {
      return callback(new Error(error.response.data[0]))
    })
  }else {
    callback(new Error('请输入合法的邮箱!'))
  }
}//邮箱
const validatePassword = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入密码'))
  }
  if(/\s/g.test(value)){
    return callback(new Error('密码不能包含空格'))
  }else {
    callback()
  }
}//密码
const passwordChange = (rule: any, value: any, callback: any) => {
  if( value ){
    if(/\s/g.test(value)){
      return callback(new Error('密码不能包含空格'))
    }
  }
  callback()
}
let rules = reactive<FormRules>({
  username: [{ required: true,validator: validateUsername, trigger: ['blur'] }],
  email: [{ required: true,validator: checkEmail, trigger: ['blur'] }],
  role_id: [{ required: true, message: '请给用户分配权限', trigger: 'change' }],
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }]
})
//修改
const validateUsernameChange = (rule: any, value: any, callback: any) => {
  let object:any = showModelStore.getSystemRowData;
  const params = reactive({
    username: addUseDialogData.value.username
  })
  if (!value) {
    callback(new Error('请输入用户名'))
  }
  if( value !== object.username ){
    if(/\s/g.test(value)){
      return callback(new Error('修改的用户名不能包含空格'))
    }else {
      usernameAndEmailExist(params).then((res: any) => {
        callback();
      }).catch(error => {
        callback(new Error(error.response.data[0]))
      })
    }
  }else{
    callback();
  }
}
//用户名
const checkEmailChange = (rule: any, value: any, callback: any) => {
  let object:any = showModelStore.getSystemRowData;
  // 邮箱正则表达式
  const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{3,6}$/
  const params = reactive({
    email: addUseDialogData.value.email
  })
  if (!value) {
    callback(new Error('请输入用户邮箱'))
  }
  if( value !== object.email ){
    if (regEmail.test(value)) {
      usernameAndEmailExist(params).then((res: any) => {
        callback();
      }).catch(error => {
        callback(new Error(error.response.data[0]))
      })
    }else {
      callback(new Error('请输入合法的邮箱!'))
    }
  }else{
    callback();
  }
}//邮箱
let rulesChange = reactive<FormRules>({
  username: [{ required: true, validator: validateUsernameChange, trigger: ['blur'] }],
  email: [{ required: true, validator: checkEmailChange, trigger: ['blur'] }],
  role_id: [{ required: true, message: '请给用户分配权限', trigger: 'change' }],
  password: [{ required: true, validator: passwordChange, trigger: 'blur' }]
})
editSystem();
function editSystem(){
  let systemRowData = showModelStore.getSystemRowData;
  if( !isEditOrAdd ){
    placeholder.value = '若不填此项，还是原来的密码';
    nextTick(()=>{
      let params = addUseDialogData.value;
      params.password = ''
      Object.assign(params,systemRowData)
    })
  }else {
    placeholder.value = '请设置密码';
    addUseDialogData.value = Object.assign({
      username: '',
      email: '',
      password: 'a123456',
      role_id: '',
      memo: '',
      id: -1
    })
  }
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  router.push({ name: 'system-user', params: { project_id: projectId } })
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let addUseDialog = JSON.parse(JSON.stringify(addUseDialogData.value));
      for (let item in addUseDialog) {
        if( !addUseDialog[item] ){
          delete addUseDialog[item]
        }
        if( item === 'role_id' && addUseDialog[item] === 1 ){
          addUseDialog.role_name = '超级管理员'
        }else if( item === 'role_id' && addUseDialog[item] === 2 ){
          addUseDialog.role_name = '普通用户'
        }
      }
      let params = Object.assign(addUseDialog);
      if( !isEditOrAdd ){
        //修改信息
        modifyUserInfo(addUseDialog.id,params).then( (res:any) => {
          ElMessage.success(`修改成功！！！`);
          loading.value = false;
          router.push({ name: 'system-user', params: { project_id: projectId } })
        }).catch(error => {
          ElMessage.error(`请求失败,提示${error}`)
        })
      }
      else {
        addUsers(params).then((res: any) => {
          ElMessage.success(`新增成员成功`)
          loading.value = false;
          router.push({ name: 'system-user', params: { project_id: projectId } })
        }).catch(error => {
          ElMessage.error(`请求失败,提示${error.data}`)
        })
      }
    } else {
      console.log('新增/修改用户失败!', fields)
    }
  })
}
</script>
<style lang="scss" scoped>
.dialog-footer {
  position: absolute;
  right: 0;
  margin-top: 10px;
}
::v-deep .el-radio__inner {
  border-radius: 0;
}
::v-deep .el-radio__input.is-checked .el-radio__inner::after {
  content: "";
  width: 10px;
  height: 5px;
  border: 2px solid white;
  border-top: transparent;
  border-right: transparent;
  text-align: center;
  display: inline-block;
  position: absolute;
  top: 2px;
  left: 2px;
  vertical-align: middle;
  transform: rotate(-45deg);
  border-radius: 0px;
  background: none;
}
</style>
